package com.alisonyu.spider.Utils;

import com.alisonyu.spider.Spider;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.WebClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 爬虫结果持久化类
 * 需要在Spider启动之后才能使用该类
 * Created by yu on 2017/9/28.
 */
public class Persistence
{
    private static WebClient client = WebClient.create(Spider.getVertx());
    //下载文件并且保存到path
    public static void download(String url,String path) {
        download(url,path,null);
    }

    public static void download(String url,String path,Runnable runnable) {
        client.getAbs(url).send(ar->{
            if(ar.succeeded()){
                try {
                    writeToFile(ar.result().body().getBytes(),path,runnable);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //将结果写入到文件中
    public static void writeToFile(String content,String path,Runnable runnable) throws IOException {
        writeToFile(content.getBytes(),path,runnable);
    }

    public static void writeToFile(String content,String path) throws IOException {
        writeToFile(content.getBytes(),path,null);
    }

    public static void writeToFile(byte[] content,String path,Runnable runnable) throws IOException {
        File file=new File(path);
        if(!file.exists()){
            if(!file.createNewFile()){
                System.err.println(path+"创建文件失败");
                return;
            }
        }
        //将写操作放到worker线程中
        Spider.workerPool.submit(()->{
            try {
                FileOutputStream fop=new FileOutputStream(file);
                fop.write(content);
                fop.flush();
                fop.close();
                if(runnable!=null){
                    runnable.run();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    public static void writeToFile(byte[] content,String path) throws IOException {
        writeToFile(content,path,null);
    }

    //写入Json文件中
    public static void writeToJson(JsonObject jsonObject,String path,Runnable runnable) throws IOException {
        writeToFile(jsonObject.toString(),path,runnable);
    }

    public static void writeToJson(JsonObject jsonObject,String path) throws IOException {
        writeToJson(jsonObject,path,null);
    }



    //输出到控制台
    public static void writeToConsole(String content){
        Spider.workerPool.submit(()->{
            System.out.println(content);
        });
    }


}
